layui.use(['layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;

    var request = GetRequest();

    //查询当前场景下的设备
    $.get("/equipment/query?sceneId=" + request.sceneId,function (data) {
        if (data.data.length != 0) {
            //加载当前场景下设备列表
            $("#barTypes").html("");
            $.each(data.data,function (i, ele) {
                if (i == 0) { //默认加载
                    $("#barTypes").append('<li class="active" data-value="'+ele.id+'">'+ele.name+'</li>');
                    init(ele.id);
                    $.get("/scene/" + ele.sceneId,function (scene) {
                        $("#barTitles").html('当前场景：' + scene.name);
                    });
                } else {
                    $("#barTypes").append('<li data-value="'+ele.id+'">'+ele.name+'</li>');
                }
            });

            $("#barTypes li").click(function () {
                $(this).addClass("active").siblings().removeClass("active");
                $("#loading").show();
                init($(this).data("value"));
            });
        } else {
            layer.msg("啊哦，找不到设备，切换场景试试？")
        }
    });

    /**
     * 初始化统计图
     * @param equipmentId
     */
    function init(equipmentId) {
        //加载设备当前通道数据
        $.get("/equipment/channel/query?equipmentId=" + equipmentId,function (channel) {
            var checkItemLength = channel.count;
            if (checkItemLength == 0) {
                return null;
            }
            window.seriesArrs = [];//记录多条通道的曲线数据
            window.xAxisdataArr = [];//x轴时间组件
            window.checkMessageArr = [];
            $("#check-item-list").html("");
            $("#barchart-box").html("");
            $.each(channel.data,function (i, ele) {
                if (ele.channelName != "设备信息" && ele.channelName != "风向") {
                    initChart(equipmentId,ele.collectChannelApplicateTypeId);
                    initBarChart(equipmentId,ele.collectChannelApplicateTypeId);
                    if (i == 0) {
                        $("#selected").html(ele.channelName);
                        $("#check-item-list").append('<li class="active" data-value="'+ ele.collectChannelApplicateTypeId +'">'+ ele.channelName +'</li>');
                        $("#barchart-box").append('<div id="barchart-'+ ele.collectChannelApplicateTypeId +'" style="display: block;width:100%;height: 100%;border: 1px solid #0E94EA;margin-top: 0.1em;"></div>');
                    } else {
                        $("#check-item-list").append('<li data-value="'+ ele.collectChannelApplicateTypeId +'">'+ ele.channelName +'</li>');
                        $("#barchart-box").append('<div id="barchart-'+ ele.collectChannelApplicateTypeId +'" style="display: none;width:5.65em;height: 3em;border: 1px solid #0E94EA;margin-top: 0.1em;"></div>');
                    }
                }
            });
            //最高最低检测项——条形统计图筛选
            $('#filBtn').on('click', function () {
                if ($('#filCon').is(":hidden")) {
                    $('#filCon').attr('style', 'display:flex');
                } else {
                    $('#filCon').hide();
                }
            });
            $(".select-div").click(function () {
                $('.select-ul').show();
            });
            $('.select-ul').on('click', 'li', function () {
                $(this).addClass('active').siblings('li').removeClass('active').parent().hide().siblings('.select-div').html($(this).html());
                $("#barchart-box").find("#barchart-" + $(this).data("value")).show().siblings().hide();
            });
            //渲染统计图
            setTrendData(xAxisdataArr,seriesArrs,checkMessageArr);
        });

        //加载额外数据
        $.get("/equipment/associate/query?equipmentId=" + equipmentId,function (data) {
            $(".vedio-display").html("");
            if (data.data.length != 0) {
                var innerHtml = '<div class="vedio-display">' +
                    '                 <video id="myPlayer" style="height: 100%;width: 100%;" poster="" controls playsInline webkit-playsinline autoplay>' +
                    '                       <source src="'+ data.data[0].deviceUrl +'" />' +
                    '                 </video>'+
                    '</div>';
                $("#vedio-display-box").append(innerHtml);
                //视频播放
                var player = new EZUIPlayer('myPlayer');
                player.on('error', function(){
                    //播放失败
                    $(".vedio-display").append('<div style="font-size: 0.5em;text-align: center;margin-top: 1.5em;">暂无数据</div>');
                });
                player.on('play', function(){
                });
                player.on('pause', function(){
                });
            } else {
                $(".vedio-display").append('<div style="font-size: 0.5em;text-align: center;margin-top: 1.5em;">暂无数据</div>');
            }
        });

    }

    /**
     * 初始化最高最低统计图——条形统计图
     * @param equipmentId
     * @param checkItemId
     */
    function initBarChart(equipmentId, checkItemId) {

        var searchObj = {};
        searchObj.page = 0;
        searchObj.limit = 5000;//设置默认最大查询范围
        searchObj.equipmentId = equipmentId;
        searchObj.checkItemId = checkItemId;

        $.get("/search/datarecord/page/query?",searchObj,function (data) {
            //当前设备的检测项目
            if (data.data.length <= 0) {
                return;
            }
            //x轴时间组件
            var xAxisdataArr = [];
            var topSeriesArr = [];//最高数据
            var lowSeriesArr = [];//最低数据
            var checkMessage = {};
            var temArr = [];
            $.each(data.data,function (i, ele) {
                var date = new Date(ele.acquisitionTime);
                var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                if (contains(xAxisdataArr,dateStr) != -1) {
                    xAxisdataArr.unshift(dateStr);
                    if (i != 0) {
                        temArr.push(tem);
                    }
                    tem = [];
                } else {
                    var processedData = parseFloat(ele.processedData);
                    tem.push(processedData);
                }

                checkMessage.legendData = ele.checkItemName;
                checkMessage.seriesName =  ele.checkItemName;
                checkMessage.yAxisformatter = ele.unit;
            });
            $.each(temArr,function (i, ele) {
                lowSeriesArr.unshift(Math.min.apply(null,ele));
                topSeriesArr.unshift(Math.max.apply(null,ele));
            });
            //删除时间数组最后一个元素
            if (xAxisdataArr.length != 0) {
                xAxisdataArr.splice(xAxisdataArr.length - 1,1);
            }
            setbarData(checkItemId,xAxisdataArr,topSeriesArr,lowSeriesArr,checkMessage);
        });
    }

    /**
     * 初始化最高最低采集项——条形统计图
     * @param checkItemId 检测项id
     * @param AxisdataArr x轴
     * @param topSeriesArr 一天内最高数据数组
     * @param lowSeriesArr 一天内最低数据数组
     * @param checkMessage 检测项信息
     */
    function setbarData(checkItemId,AxisdataArr,topSeriesArr,lowSeriesArr,checkMessage) {
        //加载最高最低检测项
        var barChart = echarts.init(document.getElementById('barchart-' + checkItemId));
        var option = {
            tooltip : {
                trigger: 'axis',
                axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                    type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            legend: {
                textStyle:{//图例文字的样式
                    color:'#cdddf7',
                },
                data:['最低' + checkMessage.legendData,'最高' + checkMessage.legendData]
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis : [
                {
                    type : 'category',
                    axisLabel: {
                        textStyle: {
                            color: '#cdddf7'
                        }
                    },
                    data : AxisdataArr
                }
            ],
            yAxis : [
                {
                    type : 'value',
                    axisLabel: {
                        textStyle: {
                            color: '#cdddf7'
                        }
                    },
                }
            ],
            color: ['#0e94eb', '#c440ef', '#efb013', '#2fda07', '#d8ef13', '#2e4af8', '#0eebc4', '#f129b1', '#17defc', '#f86363'],
            series : [
                {
                    name:'最低' + checkMessage.legendData,
                    type:'bar',
                    barWidth : 20,
                    data:lowSeriesArr
                },
                {
                    name:'最高' + checkMessage.legendData,
                    type:'bar',
                    stack: '最高' + checkMessage.legendData,

                    data:topSeriesArr
                }
            ]
        };
        barChart.setOption(option);
    }


    /**
     * 初始化采集上趋势统计图数据——折线图
     * @param equipmentId
     * @param checkItemId
     */
    function initChart(equipmentId,checkItemId) {
        var searchObj = {};
        searchObj.page = 0;
        searchObj.limit = 100;//设置默认最大查询范围
        searchObj.equipmentId = equipmentId;
        searchObj.checkItemId = checkItemId;

        $.ajax({
            url: '/search/datarecord/page/query',
            data: searchObj,
            type: 'post',
            async: false,
            success: function (data) {
                //当前设备的检测项目
                if (data.data.length <= 0) {
                    //关闭加载动画
                    layer.msg("暂无数据");
                }
                var seriesArr = [];
                var checkMessage = {};
                xAxisdataArr = [];
                $.each(data.data,function (j, ele) {
                    var date = new Date(ele.acquisitionTime);
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.push(dateStr);
                    seriesArr.push(ele.processedData);
                    checkMessage.title = ele.checkItemName + "趋势";
                    checkMessage.legendData = ele.checkItemName;
                    checkMessage.seriesName = ele.checkItemName;
                    checkMessage.yAxisformatter = ele.unit;
                });
                seriesArrs.push(seriesArr);
                checkMessageArr.push(checkMessage);
            }
        });
    }

    /**
     * 渲染统计图效果，设置检测项目相应的数据统计
     * @param xAxisdataArr x轴坐标数据
     * @param seriesArr 展示数据
     * @param checkMessageArr 检测信息
     */
    function setTrendData(xAxisdataArr, seriesArrs, checkMessageArr) {

        var lineChart = echarts.init(document.getElementById('linechart'));

        //legend数据
        function setlegendData(checkMessageArr) {
            var legendDataArr = [];
            $.each(checkMessageArr,function (i, ele) {
                legendDataArr.push(ele.legendData);
            });
            return legendDataArr;
        }

        //series数据
        function setseriesData(seriesArrs) {
            var series = [];
            $.each(seriesArrs,function (i, ele) {
                var obj = {
                        name:checkMessageArr[i].seriesName,
                        type:'line',
                        data:ele,
                        lineStyle: {
                            normal: {
                                //color:"#0f9ac3"
                                /*color: function(params) {
                                    var num = myColor.length;
                                    return myColor[params.dataIndex % num]
                                }*/
                            }
                        }
                    };
                series.push(obj);
            });
            return series;
        }

        //折线图
        var option = {
            title: {
                text: '',
                textStyle:{//图例文字的样式
                    color:'#cdddf7',
                },
                padding: [20,0,0,10],
                x:'right',
                subtext: ''
            },
            tooltip: {
                trigger: 'axis'
            },
            color: ['#0e94eb', '#c440ef', '#efb013', '#2fda07', '#d8ef13', '#2e4af8', '#0eebc4', '#f129b1', '#17defc', '#f86363'],
            legend: {
                textStyle:{//图例文字的样式
                    color:'#cdddf7',
                },
                data:setlegendData(checkMessageArr)
            },
            /*toolbox: {
                show: true,
                feature: {
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    dataView: {readOnly: false},
                    magicType: {type: ['line', 'bar']},
                    restore: {},
                    saveAsImage: {}
                }
            },*/
            grid: {
                left: '3%',
                right: '4%',
                bottom: '8%',
                containLabel: true
            },
            dataZoom: {
                show: true,
                realtime : true,
                start: 0,
                end: 18,
                height: 20,
                backgroundColor: '#f8f8f8',
                dataBackgroundColor: '#e4e4e4',
                fillerColor: '#87cefa',
                handleColor: '#87cefa',
            },
            xAxis:  {
                type: 'category',
                boundaryGap: false,
                axisLabel: {
                    textStyle: {
                        color: '#cdddf7'
                    },
                    formatter: function (value) {
                        return value + ""
                    },
                },
                data: xAxisdataArr
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    textStyle: {
                        color: '#cdddf7'
                    },
                    formatter: '{value} '
                },
                splitLine: {
                    show: false
                }
            },
            series: setseriesData(seriesArrs)
        };
        $("#loading").hide();
        lineChart.setOption(option);
    }

    /**
     * 判断数组中是否存在元素
     * @param arr
     * @param obj
     * @returns {number}
     */
    function contains(arr, obj) {
        if (arr.length != 0) {
            for (var i = 0;i < arr.length;i++) {
                if(arr[i] == obj) {
                    return -1;
                }
            }
        }
        return 0;
    }

    /**
     * 获取当前时间，以solr中date的格式 2018-08-27T02:28:58Z
     * @param date
     * @returns {string}
     */
    function getSolrDate(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
        var day = date.getDate() >= 10 ? date.getDate() : "0" + date.getDate();
        var hour = date.getHours() >= 10 ? date.getHours() : "0" + date.getHours();
        var minutes = date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes();
        var seconds = date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds();
        var dateStr = year + '-' + month + '-' + day + 'T' + hour + ':' + minutes + ':' + seconds + 'Z';
        return dateStr;
    }

    /**
     * 获取路径中的参数
     * @returns {Object}
     * @constructor
     */
    function GetRequest() {
        var url = location.search;         //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }



});